<script setup>
import { ref, onMounted } from 'vue'
import { showFailToast, showSuccessToast } from 'vant'
import api from '@/api'

const type = ref([]) // 菜谱分类
const title = ref('') // 菜谱标题
const content = ref('') // 菜谱文字描述（步骤说明）
const categoryId = ref(null) // 选择的分类ID

// 图片上传
const images = ref([]) // 存放上传的图片（第一张是封面，后面是步骤图）

onMounted(() => {
  getAllType()
})

const getAllType = () => {
  api.postReq("/category/getAll").then((res) => {
    console.log(res.data)
    let result = res.data
    if (result.code == 1) {
      type.value = result.data
    } else {
      showFailToast(result.msg)
    }
  })
}

// 提交发布菜谱
const submitRecipe = () => {
  if (!title.value || !categoryId.value || images.value.length === 0) {
    showFailToast('请完善必填项')
    return
  }

  // 组装FormData
  const formData = new FormData()
  formData.append('title', title.value)
  formData.append('categoryId', categoryId.value)
  formData.append('content', content.value)

  // 将所有图片放到myHeads[]
  images.value.forEach((img) => {
    formData.append('myHeads', img.file) // file来自uploader返回
  })

  api.postReq('/recipe/addRecipe', formData, {
    headers: { 'Content-Type': 'multipart/form-data' }
  }).then((res) => {
    let result = res.data
    if (result.code == 1) {
      showSuccessToast('发布成功')
      // 清空表单
      title.value = ''
      content.value = ''
      categoryId.value = null
      images.value = []
    } else {
      showFailToast(result.msg)
    }
  })
}
</script>

<template>
  <div class="publish-recipe">
    <van-field
        v-model="title"
        label="菜谱标题"
        placeholder="请输入菜谱标题"
        required
    />

    <van-picker
        title="选择菜谱类型"
        :columns="type.map(c => ({ text: c.name, value: c.id }))"
        @confirm="val => categoryId = val.value"
    >
      <template #default="{ text }">
        <van-field
            readonly
            clickable
            label="菜谱类型"
            :value="type.find(c => c.id === categoryId)?.name || '请选择类型'"
        />
      </template>
    </van-picker>

    <van-uploader
        v-model="images"
        multiple
        :max-count="9"
        upload-text="上传封面/步骤图"
        :after-read="file => file"
        :preview-full-image="true"
    >
    </van-uploader>
    <p class="tip">第一张图片默认为封面，后面为步骤图</p>

    <van-field
        v-model="content"
        label="菜谱内容"
        type="textarea"
        rows="5"
        placeholder="详细步骤、食材等"
    />

    <div style="margin: 16px;">
      <van-button round block type="primary" @click="submitRecipe">
        发布菜谱
      </van-button>
    </div>
  </div>
</template>

<style scoped>
.publish-recipe {
  padding: 10px;
}
.tip {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
  margin-bottom: 8px;
}
</style>
